//
//  LGKNoteMainDataModel.m
//  LGKNote
//
//  Created by 刘亚军 on 2023/5/26.
//

#import "LGKNoteMainDataModel.h"
#import "LGKConst.h"
#import "LGKNoteRespondeModel.h"
#import <XMLDictionary/XMLDictionary.h>
#import "LGKNoteMainModel.h"
#import "LGNFilterModel.h"
@implementation LGKNoteMainDataModel
- (instancetype)initWithOwnController:(YJBViewController *)ownController{
    if (self = [super initWithOwnController:ownController]){
        self.pageSize = 20;
    }
    return self;
}
- (void)yj_loadDataWithSuccess:(void (^)(BOOL))success failed:(void (^)(NSError * _Nonnull))failed{
    if (IsStrEmpty(LGKNoteManager.defaultManager.noteApi)){
        __weak typeof(self) weakSelf = self;
        [self getNoteApiWithCompletion:^(NSError *error) {
            if (error){
                failed(error);
            }else{
                [weakSelf loadDataWithSuccess:success failed:failed];
                [weakSelf getFilterParamsWithCompletion:^(BOOL isOk) {}];
            }
        }];
    }else{
        [self loadDataWithSuccess:success failed:failed];
        [self getFilterParamsWithCompletion:^(BOOL isOk) {}];
    }
}
- (void)getNoteApiWithCompletion:(void (^) (NSError *error))completion{
    NSString *url = [LGKNoteManager.defaultManager.cpbaseServerUrl yj_stringByAppendingPathComponent:[NSString stringWithFormat:@"Base/WS/Service_Basic.asmx/WS_G_GetSubSystemServerInfoForAllSubject?sysID=%@",@"S22"]];

    [[YJNetManager defaultManager].setRequest(url).setResponseType(YJResponseTypeString) startRequestWithSuccess:^(id  _Nonnull response) {
        NSDictionary *dic = [NSDictionary dictionaryWithXMLString:response];
        NSArray<NSDictionary *> *sysInfoList = [dic arrayValueForKeyPath:@"anyType"];
        if (IsArrEmpty(sysInfoList)) {
            completion([NSError yj_errorWithCode:YJErrorValueNull description:@"系统配置信息为空"]);
        }else{
            NSDictionary *dic = sysInfoList.firstObject;
            LGKNoteManager.defaultManager.noteApi = [dic objectForKey:@"WsSvrAddr"];
            completion(nil);
        }
    } failure:^(NSError * _Nonnull error) {
        completion(error);
    }];
}
- (void)loadDataWithSuccess:(void (^)(BOOL))success failed:(void (^)(NSError * _Nonnull))failed{
    __weak typeof(self) weakSelf = self;
    self.currentPage = self.startPage;
    [self.ownTableView resetFooterNoMoreData];
    [weakSelf yj_loadTableDataWithPage:weakSelf.currentPage success:^(BOOL noMore) {
        if (noMore) {
            if (weakSelf.models.count == 0) {
                success(YES);
            }else{
                if (weakSelf.models.count <= weakSelf.pageSize) {
                    [weakSelf.ownTableView endFooterRefreshingWithNoMoreData];
                }
                success(NO);
            }
        }else{
            success(NO);
        }
    } failed:^(NSError * _Nonnull error) {
        failed(error);
    }];
}
- (void)yj_loadTableDataWithPage:(NSInteger)page success:(void (^)(BOOL))success failed:(void (^)(NSError * _Nonnull))failed{
    if (self.yj_isRemoveAll) {
        [self yj_removeAllData];
    }
    NSString *NoteTitle = IsStrEmpty(self.searchKey) ? @"" : self.searchKey;
    NSString *sysID = IsStrEmpty(self.sysID) ? @"000" : self.sysID;
    NSInteger IsKeyPoint = IsStrEmpty(self.resType) ? -1 : self.resType.integerValue;
    NSString *urlStr = [LGKNoteManager.defaultManager.noteApi yj_stringByAppendingPathComponent:@"api/Note/GetNoteList"];
    NSDictionary *params = @{@"UserID":kApiParams(LGKNoteManager.defaultManager.userID),
                             @"SchoolID":kApiParams(LGKNoteManager.defaultManager.schoolID),
                             @"Token":kApiParams(LGKNoteManager.defaultManager.token),
                             @"NoteTitle":NoteTitle,
                             @"SysID":sysID,
                             @"IsKeyPoint":@(IsKeyPoint),
                             @"PageIndex":@(page),
                             @"PageNum":@(self.pageSize)};
    __weak typeof(self) weakSelf = self;
    [[YJNetManager defaultManager].setRequest(urlStr).setRequestType(YJRequestTypeGET).setParameters(params) startRequestWithSuccess:^(id  _Nonnull response) {
        LGKNoteRespondeModel *resModel = [LGKNoteRespondeModel responseModelWithData:response];
        if (resModel.isSuccess && !IsArrEmpty(resModel.Data)) {
            weakSelf.totalCount = [[resModel.Data objectForKey:@"TotalCount"] integerValue];
            NSArray *resultArr = [resModel.Data objectForKey:@"NoteList"];
            [weakSelf yj_handleResponseDataList:resultArr modelClass:LGKNoteMainModel.class totalCount:0 success:success];
        }else{
            success(YES);
        }
    } failure:^(NSError * _Nonnull error) {
        failed(error);
    }];
}
- (void)getFilterParamsWithCompletion:(void (^)(BOOL))competion{
    if (!IsArrEmpty(self.filterModels)){
        competion(YES);
        return;
    }
    NSString *urlStr = [LGKNoteManager.defaultManager.noteApi yj_stringByAppendingPathComponent:@"api/Note/GetPerNoteConfig"];
    __weak typeof(self) weakSelf = self;
    [[YJNetManager defaultManager].setRequest(urlStr).setRequestType(YJRequestTypeGET) startRequestWithSuccess:^(id  _Nonnull response) {
        LGKNoteRespondeModel *resModel = [LGKNoteRespondeModel responseModelWithData:response];
        if (resModel.isSuccess && !IsArrEmpty(resModel.Data)) {
            NSMutableArray *ids = [NSMutableArray array];
            NSMutableArray *names = [NSMutableArray array];
            for (NSDictionary *dic in resModel.Data) {
                [ids addObject:kApiParams([dic objectForKey:@"SysID"])];
                [names addObject:kApiParams([dic objectForKey:@"SysName"])];
            }
            LGNFilterModel *model = [[LGNFilterModel alloc] initWithDictionary:@{@"Title":@"系统",@"SelIndex":@(0),@"SelNames":names,@"SelIDs":ids}];
            weakSelf.filterModels = @[model];
            competion(YES);
        }else{
            competion(NO);
        }
    } failure:^(NSError * _Nonnull error) {
        competion(NO);
    }];
}
- (void)removeNoteWithNoteID:(NSString *)noteID completion:(void (^)(BOOL))competion{
    NSString *urlStr = [LGKNoteManager.defaultManager.noteApi yj_stringByAppendingPathComponent:@"api/Note/DeleteNote"];
    NSDictionary *params = @{@"UserID":kApiParams(LGKNoteManager.defaultManager.userID),
                             @"NoteID":kApiParams(noteID),
                             @"Token":kApiParams(LGKNoteManager.defaultManager.token)};
 
    [[YJNetManager defaultManager].setRequest(urlStr).setParameters(params).setRequestType(YJRequestTypeGET) startRequestWithSuccess:^(id  _Nonnull response) {
        LGKNoteRespondeModel *resModel = [LGKNoteRespondeModel responseModelWithData:response];
        if (resModel.isSuccess) {
            competion(YES);
        }else{
            competion(NO);
        }
    } failure:^(NSError * _Nonnull error) {
        competion(NO);
    }];
}
@end
